package com.holly.unit.deform.api.factory;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.holly.unit.deform.api.enums.WidgetTypeEnum;
import com.holly.unit.deform.api.pojo.tool.DesformWidget;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 类描述: 七牛云文件转换器
 *
 * @author fxr
 * @version 1.0.0
 * @date 2022/4/14 14:51
 */
public class QiniuFileConverter extends ForeseeConvert{

    private WidgetTypeEnum type;

    public QiniuFileConverter(DesformWidget widget) {
        this.type = widget.getType();
        this.model = widget.getModel();
    }

    /**
     * 文本转换为值，用于导入
     */
    @Override
    public Object converterToVal(String text) {
        if (StrUtil.isNotBlank(text)) {
            String[] urls = text.split(delimiter);
            JSONArray files = new JSONArray(urls.length);
            for (String url : urls) {
                JSONObject file = new JSONObject();
                file.put("url", url);
                // 获取文件名
                String fileName = FileUtil.getName(url);
                if (this.type == WidgetTypeEnum.IMGUPLOAD) {
                    file.put("key", fileName);
                    file.put("percent", 100);
                    file.put("status", "success");
                } else if(this.type == WidgetTypeEnum.FILE_UPLOAD) {
                    file.put("uid", System.currentTimeMillis());
                    file.put("name", fileName);
                }
                files.add(file);
            }
            return files;
        }
        return text;
    }

    /**
     * 值转换为文本，用于导出
     */
    @Override
    public String converterToTxt(String value) {
        if (StrUtil.isNotBlank(value)) {
            JSONArray files = JSON.parseArray(value);
            List<String> urls = files.stream().map(obj -> (JSONObject) obj).map(file -> file.getString("url")).collect(Collectors.toList());
            return String.join(delimiter, urls);
        }
        return value;
    }

}
